<script lang="ts" setup>
import XInput from './XInput.vue'
import { sendCode } from '@/api/user'
import type { SendCodeType } from '@/typings/api'

const { modelValue, formData, type } = defineProps<{
	send: boolean
	type: SendCodeType
	modelValue: string
	formData: {
		accept: boolean
		account: string
		graphicCaptcha: string
	}
}>()

const emit = defineEmits<{
	(e: 'update:send', value: boolean): void
	(e: 'update:modelValue', value: string): void
}>()

//获取验证码初始值
let countDown = $ref(60)
// 定时器初始值
let timer = $ref<number>()
// 是否可以点击
let disabled = $ref<boolean>(false)
// 倒计时
const countDownFun = () => {
	timer = setInterval(() => {
		countDown--
		if (countDown <= 0) {
			clearInterval(timer)
			countDown = 60
			disabled = false
		}
	}, 1000)
}

// 使用全局提示toast
const { base, success } = useToast()

// 获取验证码方法
const getCaptcha = async () => {
	if (!formData.accept) {
		base('请先同意用户协议！')
	} else if (!formData.account || !formData.graphicCaptcha) {
		base('请填写账号和图形验证码！')
	} else {
		/**
		 * 发送接口请求
		 */
		const { msg, code } = await sendCode({
			type: type,
			phone: formData.account,
			captcha: formData.graphicCaptcha
		})
		if (code !== 0) {
			base(msg || '发送失败，请稍后重试！')
		} else {
			emit('update:send', true)
			disabled = true
			countDownFun()
			success('发送成功！')
		}
	}
}

onMounted(() => {
	timer && clearInterval(timer)
})

</script>

<template>
	<XInput padding-right="32%" placeholder="请输入验证码" :model-value="modelValue"
		@update:model-value="$emit('update:modelValue', $event)">
		<view center hfull mr-2>
			<text text="30 #4d555d" :class="[disabled && 'disabled']" @click="getCaptcha">
				{{ disabled ? `${countDown}秒后重发` : '获取验证码' }}
			</text>
		</view>
	</XInput>
</template>

<style lang="scss" scoped>
.disabled {
	opacity: 0.7;
	pointer-events: none;
}
</style>